package org.asset;

import org.jocl.*;
import org.jocl.CL;
import org.jocl.CLPlatform;

public class JOCLExample {
    public static void main(String[] args) {
        // 初始化OpenCL
        CL.setExceptionsEnabled(true);
        Pointer a = Pointer.to(new float[]{1, 2, 3, 4});
        Pointer b = Pointer.to(new float[]{5, 6, 7, 8});
        Pointer c = Pointer.to(new float[4]);

        // 获取平台和设备
        CLPlatform platform = CLPlatform.getPlatform(0);
        CLDevice device = platform.getDevice(CL_DEVICE_TYPE_GPU, 0);
        CLContext context = CLContext.create(platform, new CLDevice[]{device});
        CLCommandQueue queue = CLCommandQueue.create(context, device);

        // 创建内核
        String kernelSource = "__kernel void add(__global const float *a, __global const float *b, __global float *c) {\n" +
                "    int gid = get_global_id(0);\n" +
                "    c[gid] = a[gid] + b[gid];\n" +
                "}";
        CLProgram program = CLProgram.createWithSource(context, new String[]{kernelSource});
        program.build();
        CLKernel kernel = program.createKernel("add");

        // 设置内核参数
        kernel.setArg(0, a);
        kernel.setArg(1, b);
        kernel.setArg(2, c);

        // 执行内核
        long globalWorkSize = 4;
        kernel.enqueueNDRange(queue, new long[]{globalWorkSize}, null);

        // 读取结果
        float[] result = c.get(new float[4]);
        for (float f : result) {
            System.out.println(f);
        }

        // 清理资源
        kernel.release();
        program.release();
        queue.release();
        context.release();
    }
}